<?php
/*
 * 推荐位管理控制器
 */
 namespace Admin\Controller;
 use Think\Controller;
 
 class PositionController extends CommonController {
 	public function index () {
 		 $data=array();
		 $data['status'] = array('neq',-1);
		 $page = $_REQUEST['p'] ? $_REQUEST['p']:1;
		 $pageSize = $_REQUEST['pageSize'] ?$_REQUEST['pageSize'] : 8;
		 $positions = D("Position")->getPosition($data,$page,$pageSize);
		 $positionsCount = D("Position")->getPositionCount($data);
		 
		 $res = new \Think\Page($positionsCount,$pageSize);
		 $pageRes = $res->show();
//		 print_r($pageRes);
		 $this->assign('pageRes',$pageRes);
		 $this->assign('positions',$positions);
		$this->display();
 	}
	
	public function add(){
		if($_POST){
			if(!isset($_POST['name']) || !$_POST['name'] ){
		 		return show(0, $_POST['name']);
			}
			if(!isset($_POST['description']) || !$_POST['description']){
		 		return show(0, '推荐位描述不存在');
			}
			
			if($_POST['id']){
				return $this->save($_POST);
			}
			
			$positionId = D('Position')->insert($_POST);
			if($positionId){
				return show(1,"新增成功");
			}else{
				return show(0,"新增失败");
			}
		}else{
			$this->display();
		}
	}
	
	public function del(){
		try{
			if($_POST){
				$id=$_POST['id'];
				$status=$_POST['status'];
				$res=D('Position')->updataStatusById($id,$status);
				if($res){
					return show(1, '操作成功！');
				}else{
					return show(0, '操作失败！');
				}
			}
		}catch(Exception $e){
			return show(0, $e->getMessage());
		}
		return show(0, '没有提交的数据');
	}
	
	public function save ($data){
		$positionId = $data['id'];
		unset($data['id']);
		try{
			$id=D("Position")->updataPositionById($positionId,$data);
			if($id===false){
				return show(0, '更新失败');
			}
			return show(1, '更新成功');
		}catch(Exception $e){
			return show(0, $e->getMessage());
		}
	}
	
	public function edit () {
		$positionId = $_GET['id'];
		if(!$positionId){
			//推荐位id不存在执行跳转
			$this ->rediret('/admin.php?c=position');
		}
		$position = D('Position')->getPositionById($positionId);
		if(!$position){
			//推荐位不存在执行跳转
			$this ->rediret('/admin.php?c=position');
		}
		$this->assign('position',$position);
		$this->display();
	}
 }
 
 
